package cn.piggy.gateway.core.limiter;

import org.redisson.Redisson;
import org.redisson.api.RScript;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;
import java.util.ArrayList;

public class RedisLimiter {

    private volatile static RedissonClient redissonClient;

    public static RedissonClient redisInit(String address,String password) {
        if(redissonClient==null){
            synchronized (RedisLimiter.class){
                if(redissonClient==null){
                    Config config = new Config();
                    config.useSingleServer().setAddress(address);
                    config.useSingleServer().setPassword(password);
                    StringCodec codec = new StringCodec();
                    config.setCodec(codec);
                    redissonClient = Redisson.create(config);
                }
            }
        }
        return redissonClient;
    }

    public static RedissonClient getRedissonClient(){
        return redissonClient;
    }

    public static Object runLua(){
        String string = "redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, ARGV[1])\n" +
                "local res = redis.call('zcard', KEYS[1])\n" +
                "if (res == nil) or (res < tonumber(ARGV[3])) then\n" +
                "    redis.call('zadd', KEYS[1], ARGV[2], '1')\n" +
                "    return 1\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        long time = System.currentTimeMillis();
        return redissonClient.getScript().eval(RScript.Mode.READ_WRITE,
                string, RScript.ReturnType.VALUE,
                new ArrayList<Object>(){{add("limit:rate");}}, time-1000, time, 300);
    }

}
